using Assets.Scripts.DL.Enemy.CommonEnemy;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EnemyManager : MonoBehaviour
{
    public int index;
    public GameObject enemyPrefab;

    private Controller controller;
    private bool isDestroying = false;
    private ActiveStateManager stateManager;
    void Start()
    {
        stateManager = ActiveStateManager.instance;
        init();
    }

    public void init()
    {
        if (!stateManager.getEnemyState(index))
        {
            GameObject enemy = Instantiate(enemyPrefab);
            enemy.transform.position = transform.position;
            controller = enemy.GetComponent<Controller>();
        }
    }

    void Update()
    {
        if (controller != null && controller.StateData.IsDie&&!isDestroying)
        {
            isDestroying = true;
            stateManager.setEnemyState(index, true);
            StartCoroutine(destroyEnemy(controller.gameObject));
        }
    }

    private IEnumerator destroyEnemy(GameObject gameObject)
    {
        yield return new WaitForSeconds(1);
        dropSomthing(gameObject.transform.position);
        Destroy(gameObject);
        isDestroying = false;
    }

    private void dropSomthing(Vector3 position)
    {
        DropItem dropItem = GetComponent<DropItem>();
        DropWeapon dropWeapon = GetComponent<DropWeapon>();
        if (dropItem != null)
            dropItem.dropSomething(position);
        if (dropWeapon != null)
            dropWeapon.dropSomething(position);
    }
}
